<template>
  <!-- <div style="position: relative;width:100%;height:100%"> -->
  <video
    class="video-player"
    ref="video"
    autoplay
    disablePictureInPicture
    poster="@/assets/images/loader-thumb.jpg"
  ></video>
  <!-- <TimeLine
      ref="Timeline"
      :startTime="videoConf.startTime"
      :endTime="videoConf.endTime"
      style="position: absolute; bottom: 14px; left: 0; right: 0; height: 60px"
      @timeChange="timeChange"
    ></TimeLine> -->
  <!-- </div> -->
</template>
<script setup>
  import { ref, watch, onMounted, onBeforeUnmount, defineProps, defineEmits } from 'vue';
  import dayjs from 'dayjs';

  const props = defineProps({
    // 播放类型 1实时视频，2视频回放
    playType: {
      type: String,
      default: 'realVideo'
    },
    sendType: {
      type: String,
      default: ''
    },
    index: {
      type: Number,
      default: 0
    },
    videoConf: {
      type: Object,
      default: () => {}
    },
    reconnect: {
      type: Boolean,
      default: true
    }
  });

  const emit = defineEmits(['complete']);

  const video = ref(null);
  const websocket = ref(null);
  const flag = ref(false);
  const player = ref(null);
  const heartBeatTime = ref(null);
  const times = ref(0);
  const wfs = ref(null);

  const openMsgConf = ref({});
  const closeMsgConf = ref({});
  const sendMsgConf = ref({});
  const heartBeatConf = ref({});

  watch(
    () => props.sendType,
    (newVal) => {
      if (newVal) {
        if (newVal === 'backVideoScale') return;
        const { key, parentCode1, v } = props.videoConf;
        const sendMsgObj = {
          backVideoPause: {
            t: 'backVideoPause',
            c: parentCode1,
            v: key,
            k: ''
          },
          backVideoRetPlay: {
            t: 'backVideoRetPlay',
            c: parentCode1,
            v: key,
            k: ''
          }
          // backVideoScale: {
          //   t: "backVideoScale",
          //   c: parentCode1,
          //   v: key + "|" + v,
          // },
        };
        sendMsgConf.value = sendMsgObj[newVal];
        onsend();
      }
    },
    { immediate: true }
  );

  watch(
    () => props.videoConf,
    (newVal, oldVal) => {
      console.log(newVal, 'newVal');
      if (!newVal && wfs.value) {
        closeWebsocket();
      } else {
        if (newVal) {
          setInitConf();
          initJMuxer();
          inintSocket();
        }
      }
    },
    { deep: true, immediate: true }
  );

  onMounted(() => {
    // this.$refs.Timeline.createTimeSlider(Date.now());
  });

  onBeforeUnmount(() => {
    wfs.value && wfs.value.destroy();
    clearInterval(heartBeatTime.value);
  });

  const timeChange = (e) => {
    console.log('timeChange');
    seekend(e);
  };

  const seekend = (currentTime) => {
    if (props.playType === 'realVideo') return;
    const { key, parentCode1, startTime } = props.videoConf;
    const sendMsgConf = {
      t: 'backVideoByPos',
      c: parentCode1,
      k: '',
      v: key + '|' + dayjs(currentTime).format('YYYY-MM-DD HH:mm:ss')
    };
    wfs.value.websocketLoader.onWebsocketDataUploading({
      data: JSON.stringify(sendMsgConf)
    });
    wfs.value.bufferController.reset();
    wfs.value.media.play();
  };

  const ended = (e) => {
    console.log(e, 'e');
  };

  const setInitConf = () => {
    const { channelId1, key, parentCode1 } = props.videoConf;
    const openMsgObj = {
      realVideo: {
        t: 'realVideoOpen',
        c: parentCode1,
        v: channelId1,
        k: ''
      },
      backVideo: {
        t: 'backVideoOpen',
        c: parentCode1,
        v: key,
        k: ''
      }
    };
    const closeMsgObj = {
      realVideo: {
        t: 'realVideoClose',
        c: parentCode1,
        v: channelId1,
        k: ''
      },
      backVideo: {
        t: 'backVideoClose',
        c: parentCode1,
        v: key,
        k: ''
      }
    };
    const heartBeatObj = {
      realVideo: {
        t: 'heartBeat',
        c: parentCode1,
        v: channelId1,
        k: ''
      },
      backVideo: {
        t: 'heartBeat',
        c: parentCode1,
        v: key,
        k: ''
      }
    };
    openMsgConf.value = openMsgObj[props.playType];
    closeMsgConf.value = closeMsgObj[props.playType];
    heartBeatConf.value = heartBeatObj[props.playType];
  };

  const initJMuxer = () => {
    wfs.value = new Wfs();
    window.wfs = wfs.value;
  };

  const inintSocket = (reconnect = false) => {
    console.log(socketURL, 'socketURL');
    console.log(video.value, 'video.value');
    const { c, t, v } = openMsgConf.value;
    const { protocol, host } = window.location;
    const wsProtocol = protocol === 'http:' ? 'ws://' : 'wss://';
    const socketURL = `${wsProtocol}${host}/voiceStreamWs/`;
    wfs.value.attachMedia(video.value, c, 'H264Raw', socketURL, t, v, null, (socket) => {
      emit('complete');
    });
    heartBeat();
  };

  const closeWebsocket = () => {
    const { c, v, t } = closeMsgConf.value;
    if (wfs.value) {
      wfs.value.closeWebSocket(c, t, v);
      wfs.value.websocketLoader.onWebsocketDataUploading({
        data: JSON.stringify(closeMsgConf.value)
      });
      wfs.value.websocketLoader.destroy();
    }
  };

  const onsend = () => {
    wfs.value.websocketLoader.onWebsocketDataUploading({
      data: JSON.stringify(sendMsgConf.value)
    });
  };

  const heartBeat = () => {
    // if (!wfs.value.websocketLoader.client) {
    //   return false;
    // }

    heartBeatTime.value = setInterval(() => {
      if (!wfs.value.websocketLoader.client) return false;
      if (wfs.value.websocketLoader.client.readyState === 3) {
        // WebSocket 连接已关闭
        clearInterval(heartBeatTime);
        if (wfs.value.reconnect && wfs.value.times < 3) {
          wfs.value.times++;
          // 重连socket
          initSocket(true);
        }
      } else if (wfs.value.websocketLoader.client.readyState === 1) {
        // WebSocket 连接已打开
        wfs.value.websocketLoader.onWebsocketDataUploading({
          data: JSON.stringify(heartBeatConf)
        });
        if (playType.value === 'backVideo') {
          // 获取回放视频播放进度
          wfs.value.websocketLoader.onWebsocketDataUploading({
            data: JSON.stringify({
              t: 'backVideoGetPos',
              c: videoConf.parentCode1,
              v: videoConf.key
            })
          });
        }
      }
    }, 5000);
  };
</script>
<style lang="scss" scoped>
  .video-player {
    width: 100%;
    height: 100%;
    background: #000;

    // ::v-deep .video-js {
    //   width: 100%;
    //   height: 100%;
    // }
  }
</style>
